package org.qloudgen.borg.result;

import java.sql.ResultSet;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.qloudgen.borg.CommonValues;
import org.qloudgen.borg.beans.CacheBean;
import org.qloudgen.borg.beans.Cluster;
import org.qloudgen.borg.metadb.DefaultImpl;

public abstract class AbstractResultOperator {

	static Log log = LogFactory.getLog(AbstractResultOperator.class);
	
	protected List<Map<String, String>> list;
	protected String fileName;
	protected List<String> headers;
	
	AbstractResultOperator(List<Map<String, String>> list){
		this.list = list;
	}
	
	AbstractResultOperator(String fileName,List<String> headers){
		this.fileName = fileName;
		this.headers = headers;
	}
	
	public final  void doData(String cacheID, String sql) {
		
		IDBReader db = null;

		try {		
			// get cluster info
			Cluster cluster = getClusterInfoByCacheID(cacheID);
		
			if (cluster == null) return;
			
			// query sql from cluster
			if (((String)CommonValues.props.get("mode")).equalsIgnoreCase("test")) return;  // if application mode is test, then return
			
			sql = sql.replaceAll("'null'", "'"+cacheID+"'");
			
			db = (IDBReader) Class.forName(CommonValues.DEFAULT_RESULT_READER).getConstructor(Cluster.class).newInstance(cluster);
			
			ResultSet res = db.query(sql);

			doResult(res);
			
		} catch (Exception e) {
			log.error(e.getMessage());
		} finally {
			if (db != null) db.close();
		}
	}

	private Cluster getClusterInfoByCacheID(String cacheID){
		
		// get cache info from ana_cache by cacheID
		CacheBean cacheBean = DefaultImpl.getCacheInfo(cacheID);
		
		if (cacheBean == null) return null;
		
		// get cluster info
		Cluster cluster = DefaultImpl.getClusterInfo(cacheBean.getClusterID());
		
		return cluster;
	}
	
	protected abstract void doResult(ResultSet res) throws Exception;

}
